<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('mexico.returnedRawMaterial')" :rightText="$t('distributedEnter.scanRecord')"
				@clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class=" page-auto" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<view class="gui-bg-white gui-padding-x distributed-head">
					<!--仓库-->
					<view class="custom-card-itemTwo cradItem" style="padding: 20rpx 0;">
						<text class="item-info-title" style="margin-right:50rpx"><text class="required-color">*</text>{{$t('mexico.originalWarehouse') }}：</text>
						<!-- <uni-easyinput class="uni-mt-5" style="text-align: right;" v-model="data.warehouseCode" disabled></uni-easyinput> -->
						<view style="margin-right:10px">{{ data.warehouseCode }}</view>
					</view>
					<view class="custom-card-itemTwo cradItem" style="padding: 20rpx 0;">
						<text class="item-info-title" style="margin-right:50rpx"><text class="required-color">*</text>{{ $t('mexico.returnWarehouse')}}：</text>
							<!-- <uni-easyinput class="uni-mt-5" style="text-align: right;" v-model="data.returnWarehouse" disabled></uni-easyinput> -->
							<view style="margin-right:10px">{{ data.returnWarehouse }}</view>
					</view>
					<!--库位-->
					<!--  v-if="data.locationWarehouseId.length"  -->
					<view  class="custom-card-itemTwo cradItem">
						<text class="item-info-title"><text class="required-color">*</text>{{$t('mexico.returnToStorage') }}：</text>
						<!-- 有容量的库位 -->
						<comboGrid requestUrl="/api1/wms/warehouse/QueryLocation" v-model="data.locationCode"
							:calculate="data.calculate" :requestParam="data.requestParam" inputKey="locationName"
							:placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('pageTranslation.plsInputFilter')" :column="data.columnLocation.column"
							bindValue="locationCode" @setClick="getLocationClick"></comboGrid>
					</view>
					<!-- 扫描条码部分 -->
					<view class="custom-card-itemTwo cradItem" style="padding-bottom:20rpx">
						<text class="item-info-title" style="padding-right: 40rpx;"><text
								class="required-color">*</text>{{$t('distributedEnter.barcodeScan') }}：</text>
						<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue"
							:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>
				<!-- 提示信息 -->
				<view class="gui-flex gui-rows gui-nowrap gui-align-items-center gui-margin-top">
					<view class="gui-title-line"></view>
					<text class="gui-primary-text gui-h6" style="padding-left:50rpx; padding-right:50rpx;">{{
						$t('translationImage.materialsInformation') }}</text>
					<view class="gui-title-line"></view>
				</view>
				<!-- 卡片模块 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll element-auto">
					<view style="height: 15rpx"></view>
					<view v-if="data.barcodeInfo" class="card-boxCustom">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>
								{{ $t('distributedOut.atPresent') }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCoded')
									}}：</text>{{ data.barcodeInfo.barcode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCode') }}：</text>
								{{ data.barcodeInfo.materialCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialName') }}：</text>
								{{ data.barcodeInfo.materialName }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialSpec')
									}}：</text>{{ data.barcodeInfo.materialSpec }}
							</view>
							<view class="custom-card-itemOne">
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('distributedEnter.uom') }}：</text>
									{{ data.barcodeInfo.unit }}
								</view>
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('distributedEnter.qty') }}：</text>
									{{ data.barcodeInfo.currentQty }}
								</view>
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.warehouse') }}：</text>
								{{ data.barcodeInfo.warehouseCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.location') }}：</text>
								{{ data.barcodeInfo.locationCode }}
							</view>
							<!-- <view class="custom-card-itemOne">
								<text class="item-info-title">{{$t('fgReturn.stockReturnType')}}：</text>{{ data.barcodeInfo.stockReturnTypeName }}
							</view>
							<view class="custom-card-itemOne">
								<text class="item-info-title">{{$t('fgReturn.returnType')}}：</text>{{ data.barcodeInfo.returnTypeName }}
							</view> -->
						</view>
					</view>
				</scroll-view>
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelSubmit">
						{{ $t('calendar.submit') }}</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue';
import { navigate, navigateBack } from '@/utils/routerSkip.js';
import { getDataDictionaryFn, pitchOnFn } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue';
import comboGrid from "@/components/comboGrid";
import { useStore } from "vuex";
import { onShow } from '@dcloudio/uni-app';
import { basPdaOperationLogFn } from '@/utils/index.js';
import pdaScan from '@/hooks/pdaScan.js'
import spChooseBox from '@/components/spChooseBox';
import chooseSelect from '@/components/chooseSelect';
import { onBackPress } from '@dcloudio/uni-app';
import { BIGBARCODER_PRINT ,DEFAULT_WAREHOUSECODE,DEFAULT_WAREHOUSENAME,DEFAULT_WAREHOUSEID} from '@/constant/index.js'
import superweiCombox from '@/components/superweiCombox';
import { returnToRmScan, returnToRmSubmit } from '@/api/api.js'
//JS国际化引入
import { useI18n } from 'vue-i18n';
const { t } = useI18n();

const { scan } = pdaScan()
//注册组件
components: {
	storageBin,
		comboGrid,
		spChooseBox,
		chooseSelect,
		superweiCombox
}

let store = useStore();
let data = reactive({
	scanValue: '',//扫描的条码
	returnWarehouse: 'RM', //退回仓库
	warehouseName: "", //仓库名称
	warehouseId: '',
	warehouseCode: '',
	barcodeInfo: null, //存储后端返回的数据,card的信息
	calculate: false, // 是否是容量的数据

	scanList: [],// 扫描的条码信息
	locationName: "", //库位名称
	locationId: '',
	locationCode: '',
	// 库位
	requestParam: {
		warehouseId: 0, // 设置的默认仓库
		locationCode: "",
		warehouseName:'',
		warehouseCode:'RM',
		locationName: '',
		locationTypeCode: '',
		locationTypeName: '',
		forbiddenStatus: '',
		areaCode: ''
	},
	columnLocation: {
		column: [{
			label: t('distributedOut.volumnStockName'),
			name: "locationCode",
		}]
	}
})


const navHeight = computed(() => {
	return store.state.navHeight
})

onShow(async () => {
	//没有设置默认仓库去设置默认仓库
	data.warehouseCode = uni.getStorageSync(DEFAULT_WAREHOUSECODE) || ''
	data.warehouseName = uni.getStorageSync(DEFAULT_WAREHOUSENAME) || ''
	data.warehouseId= uni.getStorageSync(DEFAULT_WAREHOUSEID) || ''
	if (data.warehouseCode == ''||data.warehouseCode=='RM') {
		uni.showModal({
			content: t('materials.pleaseSetTheDefault')+t('mexico.repositoryCannot'),
			showCancel: false,
			confirmText: t('pageTranslation.toSet'),
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/setting/warehouse'
					})
				} else if (res.cancel) {

				}
			}
		});
	}
	filter()
})


//扫描的条码信息
data.scanList = computed(() => {
	return store.state.returnedRawMaterial
})

//监听pda扫码
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		// console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
})

// 用户调起相机扫码
const iconClick = async (type) => {
	// console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}

// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}

// 获取code，查询barcode信息
const getCode = (code, type) => {
	if (!data.locationCode) {
		uni.showToast({
			title: t('pageTranslation.plsChooseLocatoinFirstly'),
			icon: 'error'
		})
		return;
	}

	//判断是否扫描过该条码
	var exist = data.scanList.filter(e => e.barcode == code);
	if (exist.length > 0) {
		uni.showToast({
			title: t('distributedOut.repeatScan'),
			icon: 'error'
		})
		return;
	}

	let parmes = {
		barcode: code,
		warehouseCode:data.returnWarehouse,
		outWarehouseCode:data.warehouseCode, 
		locationCode:data.locationCode,
	}
	returnToRmScan(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '退回原材料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		// console.log(res)
		if (res.code == 0) {
			res.data.warehouseId2 = data.warehouseId //原始仓库的id
			res.data.warehouseCode2 = data.warehouseCode //原始仓库的code
			res.data.warehouseName2 = data.warehouseName //原始仓库的name
			res.data.locationId2 = data.locationId  // 库位的id
			res.data.locationName2 = data.locationName //库位名称
			res.data.locationCode2 = data.locationCode //库位code
			res.data.returnWarehouse = data.returnWarehouse //退回仓库
			//添加到store
			data.barcodeInfo = res.data
			store.commit('addReturnedRawMaterial', data.barcodeInfo)

		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})
}

const filter = async () => {
	let locationCapacity
	await getDataDictionaryFn('LocationCapacity').then(res => {
		if (res.code == 0) {
			locationCapacity = res.data
		}
	})
	let bool = locationCapacity.some((item) => {
		return item.value == data.returnWarehouse
	})
	console.log('bool',bool)
	if (bool) {
		data.calculate = true
		data.columnLocation = {
			column: [{
				label: t('JsInternational.volumnStockName'),
				name: "locationCode",
			}, {
				label: t('pageTranslation.volumeOfLocation'),
				name: "lastInventory",
			}]
		}
	} else {
		data.calculate = false
		data.columnLocation = {
			column: [{
				label: t('JsInternational.volumnStockName'),
				name: "locationCode",
			}]
		}
	}
}
watch(() => data.returnWarehouse, (newVal, oldVal) => {
	filter()
}, {
	immediate: true,
	deep: true
});

//库位选择之后赋值给变量
const getLocationClick = (x) => {
	data.locationId = x.id
	data.locationName = x.locationName;
	data.locationCode = x.locationCode;
}


//提交
const handelSubmit = () => {
	if (!data.scanList.length) {
		uni.showToast({
			title: t('stockManage.pleaseScanCode'),
			icon: 'error'
		})
		return
	}

	let parmes = []
	data.scanList.forEach(e => {
		var obj = {
			barcode: e.barcode,
			qty: e.currentQty,
			outWarehouseCode: e.warehouseCode2,
			warehouseCode: e.returnWarehouse,
			locationCode: e.locationCode2,
			spec: e.materialSpec,
			unit: e.unit,
			materialName: e.materialName,
			materialcode: e.materialCode,
			remark: e.remark,
			deptCode: "TESTDEPT",
		}
		parmes.push(obj)
	})
	//提交数据
	returnToRmSubmit(parmes).then(res => {
		// console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '退回原材料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.code,//返回状态
				errorMessage: res.msg,//错误信息
				isPass: res.code == 0 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT,
				module: 'WMS',
				source: "PDA",
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.code == 0) {
			//删除已提交的数据
			data.scanValue = ''
			data.barcodeInfo = null
			data.barcode=''
			data.locationCode=''
			store.commit('clearReturnedRawMaterial')
		} else {
			uni.showToast({ title: res.msg, icon: "none" });
		}
	})

}


//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/refund/returnedRawMaterialRecord'
	})
}

//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit("clearReturnedRawMaterial")
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}

//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.commit("clearReturnedRawMaterial");
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})

</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

@media (prefers-color-scheme: dark) {
	.custom-card-title {
		color: #fff !important;
	}
}

.cradItem {
	margin-bottom: 20rpx;
}
</style>